from flask import request, jsonify
from flask.views import MethodView
from app.models.user import User
from app.apis.v1.auth import generate_token


class AuthTokenAPI(MethodView):
    def post(self):
        grant_type = request.form.get('grant_type')
        username = request.form.get('username')
        password = request.form.get('password')

        if grant_type is None or grant_type.lower() != 'password':
            return jsonify(success=False, message='sdf失败的token')

        user = User.query.filter_by(username=username).first()
        if user is None or not user.validate_password(password):
            return jsonify(success=False, message="账号或密码错误!")

        token, expiration = generate_token(user)

        response = jsonify({
            'success': True,
            'data': {
                'access_token': token,
                'expiration': expiration
            }
        })
        response.headers['Cache-Control'] = 'no-store'
        response.headers['Pragma'] = 'no-cache'
        return response
